package com.hugy.test.controller;

import com.alibaba.fastjson.JSON;
import com.hugy.test.annotation.PassToken;
import com.hugy.test.annotation.UserLoginToken;
import com.hugy.test.entity.TokenInfo;
import com.hugy.test.entity.User;
import com.hugy.test.entity.dto.ResponseMessage;
import com.hugy.test.service.UserService;
import com.hugy.test.util.RedisUtils;
import com.hugy.test.util.TokenUtil;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/token")
public class TokenController {
    @Autowired
    private UserService userService ;
    @Autowired
    private RedisUtils redisUtil ;
    @Autowired
    private TokenUtil tokenUtil;
    @SneakyThrows
    @PostMapping("/login")
    public ResponseMessage loginAndSetToken(User user){
        User loginUser = userService.login(user) ;
        TokenInfo tokenInfo = new TokenInfo() ;
        try {
            tokenInfo.setToken(tokenUtil.createJwtToken(loginUser));
        }catch (Exception e){
            throw new Exception("生成token失败,请重新登录") ;
        }
        tokenInfo.setUser(loginUser);
        // 向redis中存储用户信息和对应的Token
        redisUtil.setObj(loginUser.getId(),JSON.toJSONString(tokenInfo),3600*1000*60) ;
        return ResponseMessage.success("token生成成功",tokenInfo) ;
    }

    @SneakyThrows
    @UserLoginToken
    @GetMapping("/checkToken")
    public ResponseMessage checkToken(@RequestHeader(value = "token") String token){
        TokenInfo tokenInfoForRedis = JSON.parseObject(String.valueOf(redisUtil.getObj(tokenUtil.parseJWT(token).getId())),TokenInfo.class) ;
        TokenInfo tokens = new TokenInfo() ;
        if(tokenInfoForRedis != null){
            tokens.setUser(tokenInfoForRedis.getUser());
            tokens.setToken(token);
            return ResponseMessage.success("token验证成功",tokens) ;
        }else{
            throw new Exception("您已离线,请重新登录") ;
        }
    }

    @SneakyThrows
    @PassToken
    @GetMapping("/checkPass")
    public String checkPass(){
        return "ok";
    }
}

